package com.umeox.watch.moto.settings.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.utils.LanguageConfig;
import com.umeox.watch.moto.settings.R;
import com.umeox.watch.moto.settings.bean.LanguageBean;

import java.util.List;
import java.util.Locale;

public class LanguageAdapter extends RecyclerView.Adapter<LanguageAdapter.Holder> {

    private List<LanguageBean> mDatas;
    private int mSelectedPosition = -1;

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    public LanguageAdapter(List<LanguageBean> datas) {
        this.mDatas = datas;
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        final Context context = viewGroup.getContext();
        View view = LayoutInflater.from(context).inflate(R.layout.item_language, viewGroup, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, @SuppressLint("RecyclerView") int position) {
        final LanguageBean languageBean = mDatas.get(position);

        holder.mRbt.setText(LanguageConfig.initialsToUpperCase(languageBean.getLocale()));
        final boolean selection = languageBean.isSelection();
        if (selection) {
            mSelectedPosition = position;
        }
        holder.mRbt.setSelected(selection);
        holder.itemView.setOnClickListener(v -> {
            if (mSelectedPosition == position) {
                return;
            }

            if (mSelectedPosition != -1) {
                final LanguageBean lastSelectedLanguage = mDatas.get(mSelectedPosition);
                lastSelectedLanguage.setSelection(false);
                notifyItemChanged(mSelectedPosition);
            }

            mSelectedPosition = position;
            mDatas.get(mSelectedPosition).setSelection(true);
            notifyItemChanged(mSelectedPosition);
        });
    }


    class Holder extends RecyclerView.ViewHolder {
        private TextView mRbt;

        public Holder(View view) {
            super(view);
            mRbt = itemView.findViewById(R.id.rb_language);
        }
    }

    public Locale getSelectedLanguage() {
        return mDatas.get(mSelectedPosition).getLocale();
    }

}
